﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.ComponentModel;
using System.Windows.Data;
using System.Threading;

namespace Kokomo.Controls
{
	[TemplatePart(Name = PropertyListHostPartName, Type = typeof(ItemsControl))]
	public class PropertyView : ContentControl
	{
		public const string PropertyListHostPartName = "PART_PropertyListHost";

		static PropertyView()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(PropertyView), new FrameworkPropertyMetadata(typeof(PropertyView)));
		}

		public PropertyView()
		{
			//this.DataContextChanged += new DependencyPropertyChangedEventHandler(PropertyView_DataContextChanged);
		}

		//void PropertyView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
		//{
		//    this.SyncPropertyList();
		//}

		protected override void OnContentChanged(object oldContent, object newContent)
		{
			base.OnContentChanged(oldContent, newContent);

			this.Dispatcher.BeginInvoke((ThreadStart)this.SyncPropertyList);
			//this.SyncPropertyList();
		}

		private ItemsControl _propertyListPart;
		public ItemsControl PropertyListPart
		{
			get { return this._propertyListPart; }
			private set
			{
				this._propertyListPart = value;
			}
		}

		private void SyncPropertyList()
		{
			object content = this.Content;
			if (content != null)
			{
				PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(content);
				List<PropertyViewItem> items = new List<PropertyViewItem>(descriptors.Count);
				foreach (PropertyDescriptor property in descriptors)
				{
					if (property.IsBrowsable)
					{
						PropertyViewItem item = new PropertyViewItem(content, property);
						items.Add(item);
					}
				}

				ICollectionView itemsView = CollectionViewSource.GetDefaultView(items);
				itemsView.GroupDescriptions.Add(new PropertyGroupDescription("Category"));

				if (this.PropertyListPart != null)
				{
					this.PropertyListPart.ItemsSource = items;
				}
			}
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();

			object propertyListPart = this.Template.FindName(PropertyListHostPartName, this);
			this.PropertyListPart = propertyListPart as ItemsControl;

			this.SyncPropertyList();
		}
	}
}
